package com.hcy.driverapi.controller;

import com.hcy.rabbitbasicmodel.model.ReturnResult;
import com.hcy.rabbitbasicmodel.model.TokenService;
import com.hcy.rabbitbasicutils.utils.MyHttpUtils;
import com.hcy.usermodel.dto.request.UserAuthRequestDTO;
import org.apache.commons.lang.StringUtils;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

@RestController
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Value("${security.oauth2.client.access-token-uri}")
    private String accessTokenUri;
    @Value("${security.oauth2.client.client-id}")
    private String clientId;
    @Value("${security.oauth2.client.client-secret}")
    private String clientSecret;

    @Autowired
    MyHttpUtils myHttpUtils;

    @PostMapping("/login")
    public ReturnResult login(@RequestBody UserAuthRequestDTO user) {
        logger.info("login start param -> {}", ToStringBuilder.reflectionToString(user));
        //OAuth2AccessToken
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return ReturnResult.fail("用户名和密码不能为空");
        }
        String username = user.getUsername();
        String password = user.getPassword();
        // 创建 ResourceOwnerPasswordResourceDetails 对象
        ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
        resourceDetails.setAccessTokenUri(accessTokenUri);
        resourceDetails.setClientId(clientId);
        resourceDetails.setClientSecret(clientSecret);
        //处理用户名，携带更多信息 导致refresh_token 出现问题 bug
        username = username + "+" + "driver";
        resourceDetails.setUsername(username);
        resourceDetails.setPassword(password);
        // 创建 OAuth2RestTemplate 对象
        OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails);

        restTemplate.setAccessTokenProvider(new ResourceOwnerPasswordAccessTokenProvider());
        try {
            OAuth2AccessToken accessToken = restTemplate.getAccessToken();
            return ReturnResult.success("认证成功！").setData(accessToken);
        } catch (Exception e) {
            return ReturnResult.fail("用户不存在或密码错误！");
        }
    }

    @PostMapping("/refresh_token")
    public ReturnResult refresh_token(@RequestBody TokenService tokenService){
        logger.info("refresh_token start param -> {}",ToStringBuilder.reflectionToString(tokenService));
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
        map.add("grant_type","refresh_token");
        map.add("refresh_token",tokenService.getRefreshToken());
        map.add("client_id",clientId);
        map.add("client_secret",clientSecret);
        header.add("business","driver");
        return myHttpUtils.sendPostRequest(accessTokenUri, map,header);
    }

}
